'''
Description: 
Author: HowsenFisher
Date: 2021-04-12 09:52:30
LastEditTime: 2021-04-12 18:26:30
LastEditors: liutq
Reference: 
'''
import socket
import cv2
import numpy
import time

class VideoCatcher:
    def __init__(self,parent,dst_ip,port):
        self.parent = parent
        # self.parent.newInfoSignal.emit("视频捕获器初始化")
        self.ip = dst_ip
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.send()

    def setAddr(self,ip,port):
        self.ip = ip
        self.port = port

    def send(self):
        try:
            self.sock.connect((self.ip,self.port))
        except Exception:
            pass
            # self.parent.newInfoSignal.emit("视频连接失败")
        # 建立图像读取对象
        capture = cv2.VideoCapture(0)
        # 读取一帧图像，读取成功:ret=1 frame=读取到的一帧图像；读取失败:ret=0
        ret, frame = capture.read()
        # 压缩参数，后面cv2.imencode将会用到，对于jpeg来说，15代表图像质量，越高代表图像质量越好为 0-100，默认95
        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 50]
        # cv2.imshow("Sender",frame)
        while ret:
            # 停止0.1S 防止发送过快服务的处理不过来，如果服务端的处理很多，那么应该加大这个值
            time.sleep(0.01)
            # cv2.imencode将图片格式转换(编码)成流数据，赋值到内存缓存中;主要用于图像数据格式的压缩，方便网络传输
            # '.jpg'表示将图片按照jpg格式编码。
            result, imgencode = cv2.imencode('.jpg', frame, encode_param)
            # 建立矩阵
            data = numpy.array(imgencode)
            # 将numpy矩阵转换成字符形式，以便在网络中传输
            stringData = data.tostring()

            # 先发送要发送的数据的长度
            # ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串
            try:
                self.sock.send(str.encode(str(len(stringData)).ljust(16)))
            except Exception:
                return
            # 发送数据
            try:
                self.sock.send(stringData)
            except Exception:
                return
            # 读取服务器返回值
            receive = b''
            try:
                receive = self.sock.recv(1024)
            except Exception:
                return
            # 读取下一帧图片
            ret, frame = capture.read()
            cv2.putText(frame, str(receive, encoding='utf-8'), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            # cv2.imshow('Sender', frame)
            # esc退出
            k = cv2.waitKey(10) & 0xff
            if k == 27:
                break
        # self.sock.close()
        capture.release()
        # cv2.destroyAllWindows()


if __name__ == '__main__':
    myVideoCatcher = VideoCatcher("127.0.0.1",913)
